import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd/message";
import {ProductService} from "../../../shared/services/product/product.service";
import {CustomService} from "../../../shared/services/custom.service";
import {Product} from "../../../shared/model/product/entity/product";

@Component({
  selector: 'app-product-dialog',
  templateUrl: './product-dialog.component.html',
  styleUrls: ['./product-dialog.component.scss']
})
export class ProductDialogComponent implements OnInit {
    @Output() onSubmit = new EventEmitter();

    source: Product;            //input
    object: Product;       //bind object
    mode: number;           //0 for create , 1 for edit
    visible: boolean = false;

    constructor(private productService: ProductService, public customService: CustomService, private message: NzMessageService) {
    }

    ngOnInit() {
    }

    edit(object) {
        this.visible = true;
        this.source = object;
        //TODO deepcopy JSON.parse(JSON.stringify(obj))
        this.object = this.source.clone() as Product;
        this.mode = 1;

        this.visible = true;
    }

    create() {
        //TODO deepcopy JSON.parse(JSON.stringify(obj))
        this.object = new Product();
        this.mode = 0;

        this.visible = true;
    }

    submit(){
        if (this.mode === 0) {
            this.productService.create(this.object).subscribe(res => {
                if (res.result) {
                    this.object.code = res.doc.code;
                    this.onSubmit.emit({
                        result: res.result,
                        object: this.object,
                        mode: this.mode
                    });
                    this.visible = false;
                    this.message.create("success", "添加成功！");
                }
            });
        } else {
            this.productService.update(this.object).subscribe(res => {
                if (res.result) {
                    this.onSubmit.emit({
                        result: res.result,
                        object: this.object,
                        mode: this.mode
                    });
                    this.visible = false;
                    this.message.create('success', '更新成功！');
                }
            });
        }
    }

    hide() {
        this.visible = false;
    }

    compareEntity(g1: any, g2: any): boolean {
        return g1 && g2 ? g1._id === g2._id : g1 === g2;
    }

    compareElement(g1: any, g2: any): boolean {
        return g1 && g2 ? g1.code === g2.code : g1 === g2;
    }
}
